package ui

import (
	"fmt"
	"image/color"
	"lnzw/common/proto/cs_gen"
	"lnzw/engine/log"
	"lnzw/server/test/test_fyne/test_3/data"
	"lnzw/server/test/test_fyne/test_3/transport"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/dialog"
	"go.uber.org/zap"
)

type MapUI struct {
	IUIBase
	mapid    *canvas.Text
	mapscale *canvas.Text
	lines    []*canvas.Line
	mapinfo  *cs_gen.MapInfo
}

func NewMapUI(parentUI IUIBase) *MapUI {
	ui := &MapUI{
		IUIBase: parentUI,
	}
	return ui
}

func (m *MapUI) Init() {
	f := EventHandle(m.OnGetMap)
	GlobalEventMgr.Register(EventType_GetMap, &f)
}

func (m *MapUI) OnGetMap(event IEvent) {
	mapId := event.(int64)
	msg, err := transport.DefaultSyncSend("", data.MapMgrCatalog, &cs_gen.ReqMapInfo{MapId: mapId})
	if err != nil {
		log.Error("send failed", zap.Error(err))
		return
	}
	rsp, err := transport.DefaultReceive(msg)
	if err != nil {
		log.Error("unmarshal failed", zap.Error(err))
		return
	}
	rspMapInfo := rsp.(*cs_gen.ResMapInfo)
	if rspMapInfo.Result != cs_gen.ErrorCode_SUCCESS {
		dialog.ShowInformation("提示", "获取地图信息失败", m.GetWindow())
		return
	}
	m.drawGrid(rspMapInfo.MapInfo)
}

// 画格子
func (m *MapUI) drawGrid(mapinfo *cs_gen.MapInfo) {
	if m.mapid == nil {
		m.mapid = canvas.NewText("", color.Black)
		m.mapid.TextSize = 12
		m.mapid.Move(fyne.NewPos(150, 2))
		m.GetContainer().Add(m.mapid)
	}
	if m.mapscale == nil {
		m.mapscale = canvas.NewText("", color.Black)
		m.mapscale.TextSize = 12
		m.mapscale.Move(fyne.NewPos(320, 2))
		m.GetContainer().Add(m.mapscale)
	}
	m.mapid.Text = fmt.Sprintf("地图:%d", mapinfo.MapId)
	m.mapscale.Text = fmt.Sprintf("比例:%d*%d", mapinfo.Width, mapinfo.Height)
	for i := 0; i < len(m.lines); i++ {
		m.GetContainer().Remove(m.lines[i])
	}
	m.mapinfo = mapinfo
	if m.lines == nil {
		m.lines = make([]*canvas.Line, 0)
	} else {
		m.lines = m.lines[:0]
	}

	cellw := int(mapinfo.CellSize)
	width := int(mapinfo.Width)
	height := int(mapinfo.Height)
	offset_x := 150
	offset_y := 20
	for j := 0; j <= height/cellw; j++ {
		line := canvas.NewLine(color.Black)
		line.Position1 = fyne.NewPos(float32(offset_x), float32(j*cellw+offset_y))
		line.Position2 = fyne.NewPos(float32(width+offset_x), float32(j*cellw+offset_y))
		line.StrokeWidth = 1
		m.lines = append(m.lines, line)
		m.GetContainer().Add(line)
	}
	for j := 0; j <= width/cellw; j++ {
		line := canvas.NewLine(color.Black)
		line.Position1 = fyne.NewPos(float32(j*cellw+offset_x), float32(offset_y))
		line.Position2 = fyne.NewPos(float32(j*cellw+offset_x), float32(height+offset_y))
		line.StrokeWidth = 1
		m.lines = append(m.lines, line)
		m.GetContainer().Add(line)
	}
	m.GetContainer().Refresh()
}
